import { extend } from 'umi-request';
import { message } from 'antd';
import memoFn from '@/network/requestMemo';


//全局message配置
message.config({
  top: 60,
  duration: 2,
  maxCount: 3,
});
//错误处理配置
const errorHandler = (error: { response: any }) => {
  const { response } = error;
  if (response && response.status) {
    // const { status, url } = response;
    // message.error(`请求错误 ${status}: ${url}`);
  } else if (!response) {
    message.error('网络异常');
  }
  response.success = false;
  return response;
};
// console.log(window.location.protocol);//协议类型

//配置request项
export const request = extend({
  headers: {
    'Content-Type': 'application/json',
  },
  errorHandler,
  timeout: 5*1000,
  prefix: process.env.apiurl,
  // prefix: URL_PREFIX || '//localhost:6868/crmserve',
  // prefix: URL_PREFIX,
  // 默认错误处理
  //   credentials: 'include', // 默认请求是否带上cookie
});
// request拦截器, 改变url 或 options.
request.interceptors.request.use((url, options: any) => {
  let token = window.localStorage.getItem('token');
  if (!token) {
    options.headers['token'] = 'null';
  } else {
    options.headers['token'] = token;
  }
  return {
    url,
    options: { ...options, interceptors: true },
  };
});

// response拦截器, 改变response 或 options.
request.interceptors.response.use(async (response: any, options: any) => {
  const data = await response.clone().json();
  const isGet = options.method && options.method.toUpperCase() === 'GET';
  if (options?.params?.noMsg || options?.data?.noMsg) {
    if(!data.success){
      message.error(data.message || '您的请求出错啦');
    }
    //不做消息提示
  } else {
    if (data.success && !isGet) {
      message.success(data.message || '操作成功');
    } else if (!data.success) {
      message.error(data.message || '您的请求出错啦');
    }
  }

  // if (!response.headers['Access-Token']) {
  //   console.log('unlogin');
  // }
  return response;
});

// 蒋入参格式化
const formatArg = (arg: any) => {
  let p;
  if (typeof arg[0] === 'object') {
    // 项目写法入参
    const { url, method, params } = arg[0];
    p = {
      url,
      options: {
        method,
        params,
      },
      setLoading: arg[1],
    };
  } else {
    // umi 写法入参
    p = {
      url: arg[0],
      option: arg[1],
      setLoading: arg[2],
    };
  }

  return p;
};
//记录setLoading函数的队列值
const requstCount = new Map();
const resData = (...arg: any) => {
  const { url, options = { method: 'GET' }, setLoading }: any = formatArg(arg);

  options.params = { ...options.params };
  if (options.method.toUpperCase() !== 'GET') {
    options.data = { ...options.data, ...options.params };
    options.params = {};
  }

  const closeLoading = (success = true) => {
    if (!setLoading || !requstCount.get(setLoading)) return;

    if (success) {
      requstCount.set(setLoading, requstCount.get(setLoading) - 1);
      !requstCount.get(setLoading) && setLoading(false);
    } else {
      requstCount.set(setLoading, 0);
      setLoading('reload');
    }
  };
  // 防止多个请求提前结束loading
  if (typeof setLoading === 'function') {
    const count = requstCount.get(setLoading) || 0;
    requstCount.set(setLoading, count + 1);
    setLoading(true);
  }

  return request(url, options)
    .then((res: any) => {
      closeLoading();
      // requestCallBack(options, res, message,url)
      // 格式化后端返回数据 数据如果不是数组不用取data.Data
      // eslint-disable-next-line consistent-return
      return res;
    })
    .catch((e) => {
      closeLoading(false);
    });
};

let lastPostTime = 0;
let lastUrl = '';

export const requestFn =
  (params: any, setLoading: any) => (method: any, url: string, contentType: any) => {
    const options: any = {};
    options.contentType = contentType;
    options.method = method;
    options.url = url;
    options.setLoading = setLoading;

    options.params = params;
    // if (method.toUpperCase() !== 'GET' || options?.params?.noCatch) {
    // options.params.noCatch = undefined;
    if (method.toUpperCase() !== 'GET') {
      const nowTime = +new Date();
      const stopTime = 1000; // 时间内只能进行一次非get请求
      const stop = nowTime - lastPostTime < stopTime && url === lastUrl && !params?.noThrottle;
      lastUrl = url;

      lastPostTime = nowTime;
      if (stop) {
        return;
        // return { success: false };
      }
      return resData(options, setLoading);
    }
    return memoFn(() => resData(options, setLoading), options);
  };
